<template >
<div>
  <div class="userPicBox" v-show='isEditUserInfo'>
    <el-dropdown trigger="click" @command="handleCommand" size="small">
      <div class="center">
        <span class="agent">
          <img v-show="user_pic" :src="user_pic" :alt="ruleForm1.displayName" />
        </span>
        <span class="userName" :title="displayName" data-v-7moor>{{displayName}}</span>
      </div>
      <el-dropdown-menu slot="dropdown">
        <el-dropdown-item :command=item.name :disabled = item.disabled v-for="(item, index) in userDownList" :key="index">{{item.label}}</el-dropdown-item>
      </el-dropdown-menu>
    </el-dropdown>
  </div>
  <!--<div class="center" v-show="!isEditUserInfo">-->
    <!--<span class="agent">-->
      <!--<img v-show="user_pic" :src="user_pic" :alt="ruleForm1.displayName" />-->
    <!--</span>-->
    <!--<span class="userName" :title="displayName" data-v-7moor>{{displayName}}</span>-->
  <!--</div>-->

  <div id="setUserInfo" class="content-div" :class="[navMenuState ? 'navMenuState' : '' ]" style="display:none;">
    <div class="bread-crumb">
      <breadCrumb :titleArr="titleArr" @back="back('icon')"></breadCrumb>
      <i class="el-icon-close" @click.stop="back('icon')"></i>
    </div>
    <div class="set-div">
      <div v-show="isShowUserInfo">
        <affix :label="$t('userInfo.userInfo')"></affix>
        <el-form class="form-div" :model="ruleForm1" :rules="rules1" ref="ruleForm1" :label-position="labelPosition" label-width="90px">
          <el-form-item class="user_icon" :label="$t('userInfo.avatar')" v-if="flag !=='ecommerce'">
              <span class="im_icon">
                <img v-show="im_icon" :src="im_icon" :alt="ruleForm1.displayName" />
                <el-button class="userEdit" :value="ruleForm1.userEdit" id="uploadUserIcon"></el-button>
              </span>
          </el-form-item>
          <el-form-item :label="$t('public.name')" prop="displayName">
            <el-input size="mini" type="text" v-model.trim="ruleForm1.displayName" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item :label="$t('public.nickName')">
            <el-input size="mini" type="text" v-model.trim="ruleForm1.nickName" auto-complete="off"></el-input>
            <span class="tip">
                <el-tooltip
                  transition="fade-leave"
                  effect="dark"
                  :content="$t('public.nickNameTip')"
                  placement="bottom">
                  <i class="icon iconfont icon-tixingweizhi"></i>
                </el-tooltip>
              </span>
          </el-form-item>
          <el-form-item :label="$t('public.phoneNum')" prop="mobile">
            <el-input size="mini" type="text" v-model.trim="ruleForm1.mobile" auto-complete="off" :disabled="isEditPhone"></el-input>
          </el-form-item>
          <el-form-item :label="$t('public.email')" prop="email">
            <el-input size="mini" type="text" v-model.trim="ruleForm1.email" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item :label="$t('userInfo.autoBusyTime')" prop="AutoBusyTime" v-show="isAutoBusyTime && flag !== 'ecommerce'">
            <el-input size="mini" :placeholder="$t('public.pleaseEnter')" v-model.trim="ruleForm1.AutoBusyTime" auto-complete="off">
              <template slot="append">{{$t('public.seconds')}}</template>
            </el-input>
          </el-form-item>
          <el-form-item class="txrt">
            <el-button class="primary_btn" type="primary" @click="appUserInfoUpdate">{{$t('public.save')}}</el-button>
          </el-form-item>
        </el-form>
        <affix :label="$t('userInfo.changePassword')"></affix>
        <el-form  class="form-div" :model="ruleForm2" :rules="rules2" ref="ruleForm2" :label-position="labelPosition" label-width="90px">
          <el-form-item :label="$t('userInfo.oldPassWord')" prop="oldPassword">
            <el-input size="mini" type="password" v-model="ruleForm2.oldPassword" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item :label="$t('public.password')" prop="pass">
            <el-input size="mini" type="password" v-model="ruleForm2.pass" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item :label="$t('userInfo.confirmPassword')" prop="checkPass">
            <el-input size="mini" type="password" v-model="ruleForm2.checkPass" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item class="txrt">
            <el-button class="primary_btn" type="primary" @click="appUserPasswordUpdate">{{$t('public.save')}}</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div v-show="isShowNotify">
        <affix :label="$t('public.notifySet')"></affix>
        <div class="form-div">
          <notify-switch ref="notifySet" :notifySwitchRan = "notifySwitchRan"></notify-switch>
        </div>
      </div>
    </div>
  </div>
</div>
</template>
<script>
import {uploadTo7moorDomain} from '@/utils/qiniuUtils'
import * as m7Utils from '@/utils/m7Utils'
import {checkform} from '@/utils/validate'
import * as uuid from 'uuid'
import bus from '@/store/eventBus'
import notifySwitch from './NotifySwitchNew.vue'
import md5 from 'md5'
import breadCrumb from '@/components/ui-modules/breadCrumb/BreadCrumbConfig.vue'
import affix from '@/components/ui-modules/affix/Affix.vue'
// let md5 = require('md5')  class="input-div"

export default {
  name: 'UserPic',
  computed: {
    // 如果是附属工号 不能修改手机号
    isEditPhone () {
      if (this.$store.state.session && this.$store.state.session.user.inheritedFrom) {
        return true
      } else {
        return false
      }
    },
    user_pic () {
      let tempUrl = this.$store.state.session.user.im_icon ? this.$store.state.session.user.im_icon + '?imageView2/1/w/50/h/50' : ''
      return tempUrl
    },
    im_icon () {
      return this.user_icon ? this.user_icon + '?imageView2/1/w/50/h/50' : (this.$store.state.session.user.im_icon ? this.$store.state.session.user.im_icon + '?imageView2/1/w/50/h/50' : '')
    },
    _id () {
      return this.$store.state.session.sessionId
    },
    displayName () {
      return this.$store.state.session.user.displayName
    },
    labelPosition () {
      return this.$store.state.labelPosition === 'top' ? 'top' : 'right'
    },
    navMenuState () {
      return this.$store.state.navMenuState || false
    }
  },
  data () {
    var validateMobile = (rule, value, callback) => {
      if (value !== '') {
        let match = checkform(value, 'Number')
        if (match) {
          callback(new Error(this.$t(match)))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    var validateEmail = (rule, value, callback) => {
      if (value !== '') {
        let match = checkform(value, 'Email')
        if (match) {
          callback(new Error(this.$t(match)))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    var validateNum = (rule, value, callback) => {
      if (value !== '') {
        let match = checkform(value, 'Number3')
        if (match) {
          callback(new Error(this.$t(match)))
        } else {
          if (value > 60 * 60 * 24) {
            callback(new Error(this.$t('validate.afterOpTime')))
          } else {
            callback()
          }
        }
      } else {
        callback()
      }
    }
    var validateOldPass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error(this.$t('validate.enterPassword')))
      } else if (value !== this.ruleForm1.password) {
        callback(new Error(this.$t('validate.wrongPassword')))
      } else {
        callback()
      }
    }
//    let lengthRegex = new RegExp('^\\w{6,}$')
//    let characterRegex = new RegExp('[a-zA-Z]{1,}')
//    let numberRegex = new RegExp('[0-9]{1,}')
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error(this.$t('validate.enterPassword')))
      } else if (!this.regexPass(value)) {
        callback(new Error(this.$t('validate.newPasswordRule')))
      } else if (value === this.ruleForm1.password) {
        callback(new Error(this.$t('validate.checkPassword')))
      } else {
        if (this.ruleForm2.checkPass !== '') {
          this.$refs.ruleForm2.validateField('checkPass')
        }
        callback()
      }
    }
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error(this.$t('validate.enterPassword')))
      } else if (!this.regexPass(value)) {
        callback(new Error(this.$t('validate.newPasswordRule')))
      } else if (value !== this.ruleForm2.pass) {
        callback(new Error(this.$t('validate.disagreePassword')))
      } else {
        callback()
      }
    }
    return {
      flag: this.$store.getters.isEcommerce ? 'ecommerce' : 'kf',
      notifySwitchRan: Math.random(),
      initUploadFlag: false,
      isAutoBusyTime: false,
      isEditUserInfo: true,
      activeName: 'first',
      isShowUserInfo: true, // 是否显示个人信息设置
      isShowNotify: false, // 是否显示通知设置
      user_icon: '',
      ruleForm1: {
        displayName: '',
        nickName: '', // 座席昵称
        mobile: '',
        email: '',
        AutoBusyTime: '', // 后处理时长
        password: ''
      },
      ruleForm2: {
        pass: '',
        checkPass: '',
        oldPassword: ''
      },
      rules1: {
        displayName: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        mobile: [
          { validator: validateMobile, trigger: 'blur' }
        ],
        email: [
          { validator: validateEmail, trigger: 'blur' }
        ],
        AutoBusyTime: [
          { validator: validateNum, trigger: 'blur' }
        ]
      },
      rules2: {
        oldPassword: [
          { required: true, validator: validateOldPass, trigger: 'blur' }
        ],
        pass: [
          { required: true, validator: validatePass, trigger: 'blur' }
        ],
        checkPass: [
          { required: true, validator: validatePass2, trigger: 'blur' }
        ]
      },
      openIndex: 0,
      titleArr: [this.$t('public.getback')],
      m7uploaders: [],
      userDownList: [ //  个人信息下拉框
        {name: 'userInfo', label: this.$t('userInfo.userInfoConfig'), disabled: false},
        {name: 'quickReply', label: this.$t('userInfo.quickReplyConfig'), disabled: false},
        {name: 'notify', label: this.$t('public.notifySet'), disabled: false}
      ]
    }
  },
  methods: {
    regexPass (passwordNew) {
      let regexPass = false
      let lengthRegex = new RegExp('^.{8,}$') // >= 8位
      let characterRegex = new RegExp('[a-z]') // 小寫
      let characterRegex2 = new RegExp('[A-Z]') // 大寫
      let numberRegex = new RegExp('[0-9]')// 數字
      let chinese = new RegExp('[\\u4E00-\\u9FFF]+', 'g') // 是否有中文
      let num = 0
      let temporary = this.ruleForm2.pass
      temporary = temporary.replace(/[^0-9a-zA-Z]/g, '')
      if (characterRegex.test(passwordNew)) {
        num += 1
      }
      if (characterRegex2.test(passwordNew)) {
        num += 1
      }
      if (numberRegex.test(passwordNew)) {
        num += 1
      }
      if ((passwordNew.length - temporary.length) > 0) {
        num += 1
      }
      if (num >= 3) {
        regexPass = true
      } else {
        regexPass = false
      }
      if (!lengthRegex.test(passwordNew)) {
        regexPass = false
      }
      if (chinese.test(passwordNew)) {
        regexPass = false
      }
      let limitArr = ['%', '&', '"', '\'', '<', '>', '+', '=']
      for (let i = 0; i < limitArr.length; i++) {
        if (passwordNew.indexOf(limitArr[i]) > -1) {
          regexPass = false
          break
        }
      }
      return regexPass
    },
    back (flag, command) {
      let pane = document.getElementById('setUserInfo')
      if (pane) {
        if (flag === 'icon' || command === 'quickReply') {
          pane.style.display = 'none'
          return
        }
        if (pane.style.display === 'none') {
          pane.style.display = 'block'
          this.resetFields()
          this.notifySwitchRan = Math.random()
          this.initUserInfo()
        }
      }
    },
    openDialog () {
      this.user_icon = ''
      this.back()
      this.openIndex = this.openIndex + 1
    },
    handleCommand (command) { // 下拉点击事件
      if (command === 'userInfo') { // 个人信息
        this.isShowUserInfo = true
        this.isShowNotify = false
//        this.isShowQuickReply = false
        bus.$emit('showCustQuickReply', {data: false})
      } else if (command === 'notify') { // 通知设置
        this.isShowNotify = true
        this.isShowUserInfo = false
//        this.isShowQuickReply = false
        bus.$emit('showCustQuickReply', {data: false})
      } else if (command === 'quickReply') { // 快捷回复
//        this.isShowQuickReply = true
        bus.$emit('showCustQuickReply', {data: true})
        this.isShowNotify = false
        this.isShowUserInfo = false
      }
      this.back('', command)
    },
    // 更新信息
    appUserInfoUpdate (ev) {
      this.$refs.ruleForm1.validate((valid) => {
        if (valid) {
          let data = {
            displayName: this.ruleForm1.displayName,
            nickName: this.ruleForm1.nickName,
            email: this.ruleForm1.email,
            mobile: this.ruleForm1.mobile,
            AutoBusyTime: this.ruleForm1.AutoBusyTime || '0',
            im_icon: this.user_icon || this.$store.state.session.user.im_icon,
            _id: this._id
          }
          if (!this.ruleForm1.mobile) { // 若是没有手机号 && 手机方式登陆时，不让保存,（避免手机方式登陆后清空手机号然后刷新页面的操作）
            let sessionData = window.sessionStorage.getItem('loginData')
            let sessionExten = ''
            if (sessionData) {
              sessionData = JSON.parse(sessionData)
              if (sessionData.extenType) {
                sessionExten = sessionData.extenType
              }
            }
            if (sessionExten && sessionExten === 'Local') {
              this.$message.error(this.$t('userInfo.localCannotPhone'))
              return false
            }
          }
          this.$store.dispatch('userEdit', data).then(req => {
            if (req) {
              this.$message({
                message: this.$t('message.editSucess'),
                type: 'success'
              })
            }
          })
        } else {
          return
        }
      })
    },
    appUserPasswordUpdate (ev) {
      this.$refs.ruleForm2.validate((valid) => {
        if (valid) {
          let salt = this.$store.state.session.user.salt
          if (!salt) {
            let array = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
            let data = ''
            for (let i = 0; i < 6; i++) {
              data += array[Math.floor(Math.random() * 25)]
            }
            salt = data
          }
          let hexPassword = md5(this.ruleForm2.pass + salt)
          let passwordNew = this.ruleForm2.pass
          if (passwordNew !== null && passwordNew !== '') {
            let regexPass = false
            let lengthRegex = new RegExp('^.{8,}$') // >= 8位
            let characterRegex = new RegExp('[a-z]') // 小寫
            let characterRegex2 = new RegExp('[A-Z]') // 大寫
            let numberRegex = new RegExp('[0-9]')// 數字
            let chinese = new RegExp('[\\u4E00-\\u9FFF]+', 'g') // 是否有中文
            let num = 0
            let temporary = this.ruleForm2.pass
            temporary = temporary.replace(/[^0-9a-zA-Z]/g, '')
            if (characterRegex.test(passwordNew)) {
              num += 1
            }
            if (characterRegex2.test(passwordNew)) {
              num += 1
            }
            if (numberRegex.test(passwordNew)) {
              num += 1
            }
            if ((passwordNew.length - temporary.length) > 0) {
              num += 1
            }
            if (num >= 3) {
              regexPass = true
            } else {
              regexPass = false
            }
            if (!lengthRegex.test(passwordNew)) {
              regexPass = false
            }
            if (chinese.test(passwordNew)) {
              regexPass = false
            }
            let limitArr = ['%', '&', '"', '\'', '<', '>', '+', '=']
            for (let i = 0; i < limitArr.length; i++) {
              if (passwordNew.indexOf(limitArr[i]) > -1) {
                regexPass = false
                break
              }
            }
            if (!regexPass) {
              this.$message.error(this.$t('config.agent.newPasswordRule'))
              return
            }
          }
          // 去除敏感字段名 值进行base64加壳
          let sosdwarp = m7Utils.Base64.encode(this.ruleForm2.pass)
          let oldHexPassword = md5(m7Utils.Base64.encode(this.ruleForm1.password))
          let data = {
            oldHexPassword,
            sosdwarp,
            _id: this._id,
            salt,
            hexPassword
          }
          this.$store.dispatch('userEdit', data).then(req => {
            if (req) {
              this.$message({
                message: this.$t('message.editSucess'),
                type: 'success'
              })
            }
          })
        } else {
          return
        }
      })
    },
    resetFields () {
      this.$refs.ruleForm2.resetFields()// 重置
      this.$refs.ruleForm1.resetFields()
      this.$refs.ruleForm2.oldPassword = ''
    },
    // 初始化座席信息
    initUserInfo () {
      this.ruleForm1.AutoBusyTime = this.$store.state.session.user.AutoBusyTime || 0
      this.ruleForm1.nickName = this.$store.state.session.user.nickName || ''
      this.ruleForm1.email = this.$store.state.session.user.email
      this.ruleForm1.mobile = this.$store.state.session.user.mobile
      this.ruleForm1.displayName = this.$store.state.session.user.displayName
      this.ruleForm1.password = this.$store.state.session.user.password
    },
    initUploadUserIcon (ev) {
      let account = this.$store.state.session.user.account
      let that = this
      let filters = {
        mime_types: [
          { title: 'Image files', extensions: 'jpg,jpeg,gif,png,bmp' }
        ]
      }
      let fileAdded = function (up, files) {
        console.log('fileAdd')
      }
      let beforeUpload = function (up, file) {
        console.log('beforeUpload')
      }
      let uploadProgress = function (up, file) {
        console.log('uploadProgress')
      }
      let uploadComplete = function () {
        console.log('uploadComplete')
      }
      let fileUploaded = function (up, file, info) {
        let domain = up.getOption('domain')
        let res = JSON.parse(info || '{}')
        const sourceLink = that.$store.state.isUseQiniu ? (domain + res.key) : (that.$store.state.fileDomain.cos7moorTestDomain + file.fileKey)
        that.user_icon = sourceLink
      }
      let error = function (up, err, errTip) {
        console.log('uploadError ' + errTip)
        that.$message.error(errTip)
      }
      let key = function (up, file) {
        let date = m7Utils.getCurrentDate()
        let today = new Date()
        let time = today.getTime()
        let fileName = file.name
        let fileSuffix = ''
        if (fileName) {
          fileSuffix = fileName.substring(fileName.lastIndexOf('.'), fileName.length)
        }
        const cmpKey = that.$store.state.isUseQiniu ? 'icon' : 'm7-common'
        let key = account + `/${cmpKey}/` + date + '/' + time + '/' + uuid.v1() + fileSuffix
        return key
      }
      if (this.openIndex <= 1) { // 初始化加载一次，点击按钮出现弹窗加载一次
        this.m7uploaders.push(
          uploadTo7moorDomain(this.$store.state.fileDomain.cos7moorTestDomain, this.$store.state.session.user._id, 'uploadUserIcon', filters, fileAdded, beforeUpload, uploadProgress, uploadComplete, fileUploaded, error, key)
        )
        this.openIndex = this.openIndex + 1
      }
    }
  },
  components: {
    notifySwitch,
    breadCrumb,
    bus,
    affix
  },
  mounted () {
    if (!m7Utils.isHasFunc('func_user_edit_no_auto_busy_time', this.$store.state.session.user)) {
      // 座席个人设置中禁止修改后处理时长
      this.isAutoBusyTime = true
    }
    console.log(this.$store.state.session)
    if (this.$store.state.session && this.$store.state.session.user) {
      let pwd = this.$store.state.session.user.password || ''
      let exten = this.$store.state.session.user.exten || ''
      if (!isMD5(pwd)) {
        pwd = md5(pwd)
      }
      if (this.$store.state.session.user.isAdmin) {
        this.userDownList.forEach(item => {
          item.disabled = true
        })
      }
      if (m7Utils.isHasFunc('func_not_allow_user_edit_info', this.$store.state.session.user)) {
        // 禁止座席修改个人信息
//        this.isEditUserInfo = false
        this.userDownList[0].disabled = true
        if (pwd === md5(exten)) {
          this.$message({
            showClose: true,
            message: this.$t('userInfo.passwordDangerousNoPower'),
            type: 'warning',
            duration: 0
          })
        }
      } else {
        if (pwd === md5(exten)) {
          this.openDialog()
          this.$message({
            showClose: true,
            message: this.$t('userInfo.passwordDangerous'),
            type: 'warning',
            duration: 0
          })
        }
      }
    }
    this.initUploadUserIcon()
    bus.$on('showEditCustomizeReply', (msg) => {
      this.handleCommand('quickReply')
    })
  },
  watch: {
    $route (to, form) {
      let pane = document.getElementById('setUserInfo')
      if (pane) {
        pane.style.display = 'none'
      }
    }
  },
  beforeDestroy () {
    this.m7uploaders.forEach(uploader => {
      uploader &&
      uploader.destroy &&
      uploader.destroy()
    })
    bus.$off('showEditCustomizeReply')
  }
}
function isMD5 (str) {
  let md5 = /^[a-f0-9]{32}$/
  return md5.test(str)
}
</script>
<style scoped lang="stylus">
@import "../../../assets/common.styl";
.center
  padding 10px 10px 0
  white-space nowrap
  line-height 30px
  overflow hidden
  cursor pointer
.agent
  display inline-block
  float left
  margin-right 8px
  box-size(30px,30px)
  border-radius 15px
  background url("../contact-summary/img/agent.png") no-repeat 50% 50%
  background-size 30px auto
  overflow hidden
  img
    width 30px
    background-color $cf-white
.txrt
  margin-top 20px
  text-align right
.tip
  position absolute
  top 10px
  cursor pointer
  display inline-block
  height 16px
  width 16px
  border 1px solid $c-main
  text-align center
  line-height 15px
  border-radius 50%
  margin 0px 0 0 6px
  .iconfont
    border none
    font-size 10px
    color $c-main
.im_icon
  display block
  width 40px
  height 40px
  border-radius 35px
  overflow hidden
  position relative
  background url("../contact-summary/img/agent.png") no-repeat 50% 50%
  background-size 40px auto
  img
    width 40px
    background-color $cf-white
  .userEdit
    width 80px
    height 80px
    position absolute
    left 0
    top 0
    opacity 0
.userName
  display inline-block
  font-size 14px
  max-width 5em
  white-space nowrap
  text-overflow ellipsis
  overflow hidden
  vertical-align bottom
  color $cf-gray1
.content-div
  position fixed
  left 56px
  top 52px
  width calc(100vw - 56px)
  height calc(100vh - 52px)
  background-color #fff
  z-index 1001
  overflow-y auto
  .bread-crumb
    margin-bottom 20px
    position relative
    .el-icon-close
       position absolute
       right 20px
       top 12px
       color #bfcbd9
       cursor pointer
       font-weight bold
       &:hover
         color $c-main
  .set-div
    padding 3px 10px
    .form-div
      width 500px
      margin-bottom 65px
.content-div.navMenuState
  left 120px
  width calc(100vw - 120px)
.user_pic_quick_reply
  .ui-affix
    height calc(100vh - 172px)
</style>
